package com.unicom.priceboard.thread;

import java.util.HashMap;

import com.unicom.priceboard.data.hose.PutAdReader;
import com.unicom.priceboard.data.vo.PutAdElement;
import com.unicom.priceboard.util.Constants;
import com.unicom.priceboard.util.DataPath;
import com.unicom.priceboard.util.ReadFileUtil;
import com.unicom.priceboard.util.Util;

public class PutAdThread implements Runnable{

	//Path of XML file
	public static HashMap<String,PutAdElement> mapPutAd =new HashMap<String, PutAdElement>();
	private int wait = 60; //seconds
	//Buy-Sell String
	
	private static String securityPath = "";
	private String putAdSrcPath = "";
	
	public static String strBuy="";
	public static String strSell="";
	
	private int curday=-1;
	private int preday=-1;
	private boolean resetServer=true;//flag check read file for reset server
	private PutAdReader parserPutAd =new PutAdReader();
	public PutAdThread(){
		putAdSrcPath = DataPath.basePath + DataPath.putAdSrcPath;
		securityPath = DataPath.basePath + DataPath.securityPath;
		this.wait= Integer.parseInt(DataPath.hoseWait);;
	}
	public void run() {
		while(true) {
			try	{
				curday=TimerThread.CURRENT_DAY_OF_WEEK;
				 if(curday!=preday){
					 if(ReadFileUtil.isUpToDate(Util.getCurrentDataPath(securityPath))){
						 resetData();
						 preday=curday;						
					 }						
				 }	
				if(TimerThread.CURRENT_DAY_OF_WEEK!=1 && TimerThread.CURRENT_DAY_OF_WEEK!=7) {
					if(TimerThread.CURRENT_TIME>=1030 &&TimerThread.CURRENT_TIME<1115) {
							resetServer=false;
							int marketState=Integer.parseInt(MarketStatusThread.getCurrentMarketState());
							 if(ReadFileUtil.isUpToDate(Util.getCurrentDataPath(putAdSrcPath))){
								if(marketState>=Integer.parseInt(Constants.MARKET_STATE_PTD_SESSION)&& marketState !=Integer.valueOf(Constants.MARKET_STATE_PRE_OPEN)){
									parserPutAd.ParserAd(putAdSrcPath);
								}//end if
							 }
					}else if(mapPutAd.size()==0 && resetServer){
						resetServer=false;
						int marketState=Integer.parseInt(MarketStatusThread.getCurrentMarketState());
						if(marketState>=Integer.parseInt(Constants.MARKET_STATE_PTD_SESSION)&& marketState !=Integer.valueOf(Constants.MARKET_STATE_PRE_OPEN)){
							parserPutAd.ParserAd(putAdSrcPath);
						}
					}
				}else if(mapPutAd.size()==0) {					
					parserPutAd.ParserAd(putAdSrcPath);
				}
			}catch(Exception e) {
				
				}
			
			//wait a period before continue to read
			try {
				Thread.sleep(1000*wait);
			} catch (Exception e) {
			}
		}
	}
	//reset data
	private void resetData(){		
		 mapPutAd.clear();
		 strBuy="";
		 strSell="";
	}
	
}
